/**
 * 2017年5月18日
 */
package cn.edu.bjtu.net;

import java.util.concurrent.TimeUnit;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.DynamicChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpMessage;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.HttpVersion;

/**
 * @author Alex
 *
 */
public class ServerHandler extends MessaageHandler {
	Channel channel;
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		if(e.getMessage() instanceof String){
			System.out.println(e.getMessage());
		}else if(e.getMessage() instanceof HttpMessage){
			HttpMessage mess = (HttpMessage) e.getMessage();
			System.out.println(mess.getContent());

		}else{
			System.out.println(e.getMessage().getClass().toString());
		}
		super.messageReceived(ctx, e);
	}
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		System.out.println("server connected!!");
		super.channelConnected(ctx, e);
		new Thread(()->{
			while(true){
				Channel c = ctx.getChannel();
				HttpResponse hr = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
				ChannelBuffer cb = new DynamicChannelBuffer(1000);
				cb.writeBytes("what the fuck".getBytes());
				hr.setContent(cb);
				c.write(hr);
				try {
					TimeUnit.SECONDS.sleep(1);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		}).start();
		
	}
	@Override
	public void sendMessage(String message) {
		if(channel!=null && channel.isConnected()){
			HttpResponse hr = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
			ChannelBuffer cb = new DynamicChannelBuffer(1000);
			cb.writeBytes(message.getBytes());
			hr.setContent(cb);
			channel.write(hr);
		}
	}
}
